//
//  PayViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/31.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "PayViewController.h"
#import "PayHeadCell.h"
#import "PayReminderCell.h"
#import "PayListCell.h"
#import "PayResultViewController.h"
#import "MineAllOrderViewController.h"
#import "MineViewController.h"
#import "RuleViewController.h"
@interface PayViewController ()<UITableViewDelegate, UITableViewDataSource>

{
    dispatch_source_t _timer;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *sureBtn;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, copy) NSString *secretKey;//秘钥  支付宝所用

@property (nonatomic, copy) NSString *flagStr;//标识符
@property (nonatomic, copy) NSDictionary *param;
@property (nonatomic, strong) UILabel *timeLabel;//右上角倒计时

@property (nonatomic, copy) NSString *select;//判断确定支付按钮是否可以点击  当倒计时结束后


@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付订单";
//    [self addBackItem];
    _select = @"1";
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backItemAction)];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    _timeLabel.textColor = ColorFrom16(0xF5CB37);
    _timeLabel.font = PFMFONT(18);
    _timeLabel.textAlignment = 2;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_timeLabel];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, 302 + 65) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[PayHeadCell class] forCellReuseIdentifier:@"head"];
    [_tableView registerClass:[PayReminderCell class] forCellReuseIdentifier:@"reminder"];
    [_tableView registerClass:[PayListCell class] forCellReuseIdentifier:@"list"];
    [self.view addSubview:_tableView];
    
    _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sureBtn setTitle:@"确认支付" forState:0];
    [_sureBtn setTitleColor:ColorFrom16(0x202020) forState:0];
    _sureBtn.titleLabel.font = PFRFONT(16);
    _sureBtn.layer.backgroundColor = ColorFrom16(0xf0f0f0).CGColor;
    _sureBtn.layer.cornerRadius = 7;
    [_sureBtn addTarget:self action:@selector(handleSureBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sureBtn];
    [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tableView.mas_bottom).offset(29);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@44);
    }];
    
    [self alertView];
    
    [self payNetwork];
    
    
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/order/getPayOrder?orderSn=%@", GW_Domain, self.orderId] parameters:@{@"orderSn":self.orderId} completionBlockWithSuccess:^(NSDictionary *resultDict) {
        
        NSLog(@"获取图片 %@", resultDict);
        self.imageUrl = resultDict[@"data"][@"goods_img"];
        self.goodsName = resultDict[@"data"][@"goods_name"];
        self.sale_price = resultDict[@"data"][@"price"];
        [self dateTimer:resultDict[@"data"][@"stime"]];
        [_tableView reloadData];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
    
}

- (void)dateTimer:(NSString *)end_time
{
    //当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //HH:mm:ss
    //    formatter.timeZone = [NSTimeZone localTimeZone];
    NSString *localString = [formatter stringFromDate: [NSDate date]];

    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *endDate = [dateFormatter dateFromString:end_time];
    NSDate *startDate = [dateFormatter dateFromString:localString];
    
    NSDate *endDate_tomorrow = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([endDate timeIntervalSinceReferenceDate])];
    NSTimeInterval timeInterval = [endDate_tomorrow timeIntervalSinceDate:startDate];
    
    if (_timer==nil) {
        __block int timeout = timeInterval; //倒计时时间
        
        if (timeout!=0) {
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    self.select = @"0";//判断按钮是否可以点击
                    _timer = nil;
                    dispatch_async(dispatch_get_main_queue(), ^{
                    });
                }else{
                    int days = (int)(timeout/(3600*24));
                    if (days==0) {
//                        self.dayNumberLabel.text = @"";
                    }
                    int hours = (int)((timeout-days*24*3600)/3600);
                    int minute = (int)(timeout-days*24*3600-hours*3600)/60;
                    int second = timeout-days*24*3600-hours*3600-minute*60;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.timeLabel.text = [NSString stringWithFormat:@"%d:%d",minute, second];
                        
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        }
    }
    
    
}



- (void)backItemAction
{
    MineAllOrderViewController *all = [MineAllOrderViewController new];
    all.titleName = @"待付款";
    all.status = @"0";//待付款
    all.flag = @"订单";
    [self.navigationController pushViewController:all animated:YES];
}

- (void)delayAction
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)payNetwork
{
    //支付宝
    NSDictionary *param = @{@"order_sn" : STRING(self.orderId),
                            @"pay_type" : @"2"};
    [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/order/AlipayPayOrder", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"支付宝%@", resultDict);
        NSDictionary *dic = resultDict[@"data"];
        _secretKey = dic[@"alipayStr"];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
    
    
    
    NSDictionary *parama = @{@"order_sn" : STRING(self.orderId),
                             @"pay_type" : @"1"};
    //微信
    [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/order/AlipayPayOrder", GW_Domain] parameters:parama completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"微信 %@", resultDict);
        _param = resultDict[@"data"];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
    }];
}

- (void)alertView
{
    _bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _bgView.hidden = YES;
    _bgView.layer.backgroundColor = ColorFrom16A(0x000000, 0.8).CGColor;
    _bgView.layer.cornerRadius = 12;
    [self.navigationController.view addSubview:_bgView];
//    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(64);
//        make.left.and.right.and.bottom.equalTo(self.view);
//    }];
    
    UIView *view = [UIView new];
    view.backgroundColor = ColorWhite;
    [_bgView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(164+140));
        make.width.equalTo(@270);
        make.centerX.equalTo(_bgView.mas_centerX);
        make.centerY.equalTo(_bgView.mas_centerY);
    }];
    
    UIImageView *imageview = [UIImageView new];
    imageview.image = IMAGE(@"comment_log");
    imageview.userInteractionEnabled = YES;
    [view addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view);
        make.left.and.right.equalTo(view);
        make.height.equalTo(@140);
    }];
    
    //关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:IMAGE(@"close") forState:0];
    [closeBtn setEnlargeEdge:20];
    [closeBtn addTarget:self action:@selector(handleCloseBtn) forControlEvents:UIControlEventTouchUpInside];
    [imageview addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageview).offset(11);
        make.right.equalTo(imageview).offset(-11);
        make.width.equalTo(@11);
        make.height.equalTo(@11);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"您还不是派乐宝会员";
    titleLabel.textColor = ColorFrom16(0x323232);
    titleLabel.font = PFRFONT(16);
    [view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageview.mas_bottom).offset(15);
        make.centerX.equalTo(view.mas_centerX);
        make.width.greaterThanOrEqualTo(@143);
        make.height.equalTo(@22);
    }];
    
    UILabel *detailLabel = [UILabel new];
    detailLabel.text = @"进入“我的“个人页面,派乐宝会员入口注册成为派乐宝会员，即可享受会员权益。";
    detailLabel.textColor = ColorFrom16(0x7F7E7D);
    detailLabel.font = PFRFONT(12);
    detailLabel.textAlignment = 1;
    detailLabel.numberOfLines = 3;
    [view addSubview:detailLabel];
    [detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(10);
        make.centerX.equalTo(view.mas_centerX);
        make.width.equalTo(@180);
        make.height.equalTo(@51);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"成为会员" forState:0];
    [btn setTitleColor:ColorFrom16(0x323232) forState:0];
    btn.titleLabel.font = PFRFONT(16);
    btn.layer.backgroundColor = ColorFrom16(0xFEDE6D).CGColor;
    btn.layer.cornerRadius = 4;
    [view addSubview:btn];
    [btn addTarget:self action:@selector(handleBtn) forControlEvents:UIControlEventTouchUpInside];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(detailLabel.mas_bottom).offset(10);
        make.width.equalTo(@180);
        make.centerX.equalTo(view.mas_centerX);
        make.height.equalTo(@44);
    }];
}

//成为会员的响应方法
- (void)handleBtn
{
    
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.hidden = YES;
    }];
    [self.navigationController pushViewController:[RuleViewController new] animated:YES];
//    [self.navigationController popToRootViewControllerAnimated:YES];
}

//关闭按钮的响应方法
- (void)handleCloseBtn
{
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.hidden = YES;
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
        return 116;
    else if(indexPath.row == 1)
        return 50;
    else
        return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        PayHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"head"];
        cell.priceLabel.text = self.sale_price;
        cell.detaiLabel.text = self.goodsName;
        [cell.iv sd_setImageWithURL:[NSURL URLWithString:self.imageUrl]];
        return cell;
    }
    else if(indexPath.row == 1)
    {
        PayReminderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reminder"];
        return cell;
    }
    else
    {
        PayListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
        switch (indexPath.row) {
            case 2:
                cell.label.text = @"微信支付";
                cell.wxImg.image = IMAGE(@"weixin");
                break;
            case 3:
                cell.label.text = @"支付宝支付";
                cell.wxImg.image = IMAGE(@"pay");
                break;
            case 4:
                cell.label.text = @"派乐宝支付";
                cell.wxImg.image = IMAGE(@"pailebao");
                cell.reminderLabel.hidden = NO;
                break;
                
            default:
                break;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            break;
        case 1:
            break;
        case 2:
        {
            _sureBtn.backgroundColor = ColorFrom16(0xFEDE6D);
            _flagStr = @"微信支付";
        }
            break;
        case 3:
        {
            _sureBtn.backgroundColor = ColorFrom16(0xFEDE6D);
            _flagStr = @"支付宝支付";
            
        }
            break;
        case 4:
        {
//            if([USER_VIP isEqualToString:@"未开通"])
//            {
//                NSLog(@"%@", USER_VIP);
//                _bgView.hidden = NO;
//            }
//            else
//            {//已开通
//                _bgView.hidden = YES;
                _flagStr = @"派乐宝支付";
//            }
            _sureBtn.backgroundColor = ColorFrom16(0xFEDE6D);
        }
            break;
        default:
            break;
    }
}

/***
 * 确定支付的响应按钮
 */
- (void)handleSureBtn
{
    if([_select isEqualToString:@"0"])
    {
        MESSAGE_TOAST(@"订单已取消");
        return;
    }
    if([_sureBtn.backgroundColor isEqual:ColorFrom16(0xf0f0f0)])
    {
        MESSAGE_TOAST(@"请选择支付方式");
        return;
    }
    AlertViewManager *alert = [[AlertViewManager alloc] initWithTitle:@"是否确认支付" message:nil cancelButtonTitle:@"取消" confirmButtonTitle:@"确定" delegate:nil block:^(NSInteger idx) {
        if(idx == 1)
        {
            if([_flagStr isEqualToString:@"微信支付"])
            {
                //微信支付
                [[ShareView sharedInstance] payWithWxDict:_param andCallback:^{
                    //进入block就说明支付成功了
                    PayResultViewController *payVC = [PayResultViewController new];
                    payVC.ordersn = self.orderId;
                    [self.navigationController pushViewController:payVC animated:YES];
                }];
            }
            else if ([_flagStr isEqualToString:@"支付宝支付"])
            {
                
                [GW_Pay alipayPay:_secretKey fromScheme:@"PaiLeXiong" andblock:^(NSDictionary *dcit) {
                    NSLog(@"%@", dcit);
                    if ([dcit[@"resultStatus"] isEqualToString:@"9000"]) {
                        //支付成功,这里放你们想要的操作
                        PayResultViewController *payVC = [PayResultViewController new];
                        payVC.ordersn = self.orderId;
                        [self.navigationController pushViewController:payVC animated:YES];
                    }
                    else
                        MESSAGE_TOAST(dcit[@"memo"]);
                }];
                
            }
            else if ([_flagStr isEqualToString:@"派乐宝支付"])
            {
                if([USER_VIP isEqualToString:@"未开通"])
                {
                    _bgView.hidden = NO;
                    return ;
                }
                
                [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/order/PailePayOrder", GW_Domain] parameters:@{@"order_sn":self.orderId} completionBlockWithSuccess:^(NSDictionary *resultDict) {
                    NSLog(@"派乐宝支付成功 %@", resultDict);
                    
                    PayResultViewController *payVC = [PayResultViewController new];
                    payVC.ordersn = self.orderId;
                    [self.navigationController pushViewController:payVC animated:YES];
                    
                } andFailure:^(NSError *error, NSString *errorMsg) {
                    NSLog(@"%@", error);
                }];
                
            }
        }
        else
        {
            return ;
        }
    }];
    [alert show];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.navigationBar.barTintColor = ColorWhite;
    [self.navigationController.navigationBar setShadowImage:nil];

}

- (void)viewWillDisappear:(BOOL)animated
{
//    [self.navigationController.navigationBar setHidden:NO];
    
//    [[UINavigationBar appearance] setTranslucent:YES];//设置导航条透明
    
    //设置导航栏背景图片为一个空的image，这样就透明了
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
